package com.hjli.websocket;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hjli.tuling.TuRingTool;

@ServerEndpoint("/chatserver/{userId}")
public class WebSocketServer {
	private static Map<String, Session> sessionMap = new HashMap<String, Session>();// 在线的客户端session集合，只在第一次new的时候初始化。

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@OnMessage
	public void onMessage(String message, Session session, @PathParam(value = "userId") String userId)
			throws Exception {

		if(message.contains("@Robot")||message.contains("@机器人")){
			TuRingTool turing = new TuRingTool();
//			List<String> listString = JSON.parseArray(turing.noSecretSend(message), String.class);  
	
			String sendMessage = turing.noSecretSend(message).split("text")[1].replaceAll(":","").replaceAll("\"","").replaceAll("}","");
			session.getBasicRemote().sendText( "<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color:green;\">(<span style=\"color:blue;\">"+ userId +"</span>) "+" "+ sdf.format(new Date()) +" </span><br/> &nbsp;&nbsp;&nbsp;&nbsp;"  +message+"</p>");
			session.getBasicRemote().sendText( "<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color:green;\"><span style=\"color:blue;\">机器人</span> "+" "+ sdf.format(new Date()) +" </span><br/> &nbsp;&nbsp;&nbsp;&nbsp;"  +sendMessage+"</p>");
//			System.out.println(sendMessage);
		}else{
			try {
				Iterator<String> it = sessionMap.keySet().iterator();
				// 循环给每个客户端发送信息
				while (it.hasNext()) {
					String key = (String) it.next();
					Session value = sessionMap.get(key);
					value.getBasicRemote().sendText( "<p>&nbsp;&nbsp;&nbsp;&nbsp;<span style=\"color:green;\">(<span style=\"color:blue;\">"  + userId +  "</span>) "+" "+ sdf.format(new Date()) +" </span><br/> &nbsp;&nbsp;&nbsp;&nbsp;"  + message+"</p>");
				}
			} catch (Exception e) {
				System.out.println("接收消息事件异常!");
			}
		}
		
	}

	@OnOpen
	public void onOpen(Session session, @PathParam(value = "userId") String userId) throws Exception {
		// System.out.println("打开连接成功！");
		sessionMap.put(userId, session);
		
		// System.out.println("用户" + userId + "进来了。。。");
		// System.out.println("当前在线人数：" + sessionMap.size());
		try {
			Iterator<String> it = sessionMap.keySet().iterator();
			// 循环给每个客户端发送信息
			while (it.hasNext()) {
				String key = (String) it.next();
				Session value = sessionMap.get(key);
				value.getBasicRemote().sendText("<h5 style=\"color:blue;text-align:center;\">系统消息：(" + userId + ") 已进入聊天室</h5>");
//				value.getBasicRemote().sendText( " (" + sdf.format(new Date()) + " )"+" " + userId + " ：<br/> "  + message);
			}
		} catch (Exception e) {
			System.out.println("接收消息事件异常!");
		}
	}

	/**
	 * 关闭连接事件
	 */
	@OnClose
	public void onClose(Session session, @PathParam(value = "userId") String userId) {
		sessionMap.remove(userId);
		try {
			Iterator<String> it = sessionMap.keySet().iterator();
			// 循环给每个客户端发送信息
			while (it.hasNext()) {
				String key = (String) it.next();
				Session value = sessionMap.get(key);
				value.getBasicRemote().sendText("<h5 style=\"color:red; text-align:center;\">系统消息：(" + userId + ") 已离开聊天室</h5>");
//				value.getBasicRemote().sendText( " (" + sdf.format(new Date()) + " )"+" " + userId + " ：<br/> "  + message);
			}
		} catch (Exception e) {
			System.out.println("接收消息事件异常!");
		}
	}

	/**
	 * 错误信息响应事件
	 * 
	 * @param session
	 * @param throwable
	 */
	@OnError
	public void OnError(Session session, Throwable throwable, @PathParam(value = "userId") String userId) {
		System.out.println("异常消息：" + throwable.getMessage());
	}
}
